<!--
 * @Author: zhayang
 * @LastEditors: zhayang 1063975710@qq.com
 * @Date: 2024-06-28 23:34:02
 * @LastEditTime: 2024-07-12 00:35:10
 * @Description: 添加视频
-->
<template>
  <FormLayout title="添加视频">
    <div class="form-area fit overflow-hidden">
      <div class="full-w flex m-b-28">
        <div class="flex-1">
          <div class="text-#1c1f23 text-14 line-height-22 m-b-8 font-400">
            上传视频
          </div>
          <UpVideo
            url=""
            :video-flag="false"
            up-text="点击上传视频"
            @getFile="getFile"
            @getImg="getImg"
          />
        </div>
        <div class="flex-1">
          <div class="text-#1c1f23 text-14 line-height-22 m-b-8 font-400">
            视频封面
          </div>
          <UpImgList
            class="w-120 h-120"
            :url="formState.cover_url"
            up-text="点击上传图片"
            img-show
            @deleteImg="setImg('')"
            @getImg="setImg"
          />
        </div>
      </div>
      <div class="full-w m-b-20">
        <div class="text-#1c1f23 text-14 line-height-22 m-b-8 font-400">
          视频名称
        </div>
        <Input
          v-model="formState.title"
          placeholder="请输入"
        />
      </div>
      <div class="full-w m-b-20">
        <div class="text-#1c1f23 text-14 line-height-22 m-b-8 font-400">
          视频描述
        </div>
        <Input
          v-model="formState.intro"
          placeholder="请输入"
        />
      </div>
      <div class="full-w">
        <div class="text-#1c1f23 text-14 line-height-22 m-b-8 font-400">
          关联合集
        </div>
        <Select
          v-model="formState.series_id"
          placeholder="请选择"
          size="medium"
          style="width: 100%"
          :options="options"
        />
      </div>
    </div>
    <template #footer>
      <el-button
        size="small"
        :loading="loading"
        @click="cancel"
      >
        取消
      </el-button>
      <el-button
        type="primary"
        size="small"
        :loading="loading"
        @click="save"
      >
        保存
      </el-button>
    </template>
  </FormLayout>
</template>

<script>
import FormLayout from '@/components/bmp/layout/form-layout.vue'
import UpVideo from '@/components/upload/up-video2.vue'
import UpImgList from '@/components/upload/up-image-list.vue'
import { getCollectList, addVideo } from '@/api/video'
import { Select, Input } from '@/components/bmp/form/index'

import { Loading } from 'element-ui'
import axios from 'axios'
import { getToken } from '@/utils/auth'
export default {
  components: {
    FormLayout,
    UpVideo,
    UpImgList,
    Select,
    Input
  },
  data() {
    return {
      formState: {
        title: '',
        media_url: '',
        intro: '',
        cover_url: '',
        series_id: ''
      },
      options: [],
      loading: false,
      dialogVisible: false
    }
  },
  created() {
    this.getData()
    if (this.$route?.query?.uid) {
      const id = this.$route.query?.uid || ''
      this.formState.series_id = +id
    }
  },
  methods: {
    getData() {
      getCollectList()
        .then((res) => {
          if (res && res.code === 0) {
            this.options = (res?.data || []).map((i) => {
              return {
                label: i.title,
                value: i.id
              }
            })
          }
        })
        .catch(() => {
          this.$message.error('获取错误，请重试')
        })
    },
    cancel() {
      this.$router.go(-1)
    },
    getFile(e) {
      this.formState.media_url = e
    },
    generateUUID() {
      const timestamp = Date.now().toString(16)
      const random = Math.random().toString(16).slice(2)
      return `${timestamp}${random}`
    },
    getImg(e, stsData) {
      const name = '视频封面' + new Date().getTime()
      const byteCharacters = atob(e.split(',')[1])
      const byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)
      const blob = new Blob([byteArray], { type: 'image/png' })

      // 创建一个新的File对象
      const file = new File([blob], `${name}.png`, {
        type: 'image/png'
      })
      const signature = stsData.mp.signature
      const ossAccessKeyId = stsData.body.AccessKeyId
      const policy = stsData.mp.policy
      const key = stsData.file_path + this.generateUUID() + '.png'
      const securityToken = stsData.body.SecurityToken
      const formData = new FormData()
      formData.append('name', name) // 文件名称
      formData.append('key', key) // 存储在oss的文件路径
      formData.append('OSSAccessKeyId', ossAccessKeyId) // //accessKeyId
      formData.append('policy', policy) // policy
      formData.append('Signature', signature) // 签名
      formData.append('x-oss-security-token', securityToken) // 使用STS签名时必传。
      formData.append('success_action_status', 200)
      formData.append('file', file, name) // 如果是base64文件，那么直接把base64字符串转成blob对象进行上传即可
      axios
        .post(stsData.host, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Auth-Token': getToken()
          }
        })
        .then((rep) => {
          // console.log('rep', rep)
          if (rep.status === 200) {
            this.formState.cover_url = stsData.host + '/' + key
          }
        })
        .catch((err) => {
          throw err
        })
    },
    setImg(e) {
      this.formState.cover_url = e
    },
    save() {
      if (this.formState.media_url) {
        this.loading = true
        const loadingInstance = Loading.service()
        addVideo({
          ...this.formState
        })
          .then((res) => {
            if (res && res.code === 0) {
              this.$message.success('创建成功')
              this.$router.go(-1)
            }
          })
          .catch(() => {
            this.$message.error('创建失败请重试！')
          })
          .finally(() => {
            this.loading = false
            this.$nextTick(() => {
              loadingInstance.close()
            })
          })
      } else {
        this.$message.warning('请上传视频！')
      }
    }
  }
}
</script>
<style lang="scss" scoped></style>
